﻿using System;
using EPiServer;
using EPiServer.Core;
using EPiServer.Framework;
using TemplateFoundation.Configuration;
using TemplateFoundation.Core;
using TemplateFoundation.Core.ContentStructure;
using TemplateFoundation.PageTypes;

namespace TemplateFoundation.EventHandlers
{
    /// <summary>
    /// Handles date folder sorting for articles published under the news container
    /// </summary>
    /// <remarks>Can be disabled through site settings</remarks>
    [InitializableModule]
    [ModuleDependency(typeof(PageTypeBuilder.Initializer))]
    public class ArticlesDateFolderSorter : IInitializableModule
    {
        private bool _creatingPageEventAttached;

        #region IInitializableModule Members

        /// <summary>
        /// Attaches event handlers
        /// </summary>
        /// <param name="context">The context.</param>
        public void Initialize(EPiServer.Framework.Initialization.InitializationEngine context)
        {
            if (!_creatingPageEventAttached)
            {
                DataFactory.Instance.CreatingPage += CreatingPage;
                DataFactory.Instance.PublishingPage += PublishingPage;
            }

            _creatingPageEventAttached = true;
        }

        void PublishingPage(object sender, PageEventArgs e)
        {
            if (!(e.Page is ArticlePageBase) || !IsPageUnderNewsContainer(e.Page) || !DateFolderSortingIsEnabled())
            {
                return;
            }

            new DateFolderStructure(Settings.Instance.NewsContainer, false, true, Settings.Instance.DateFolderPageTypeId.Value,"PageStartPublish").PutInDateFolder(e.Page);
        }

        void CreatingPage(object sender, PageEventArgs e)
        {
            if (!(e.Page is ArticlePageBase) || !IsPageUnderNewsContainer(e.Page) || !DateFolderSortingIsEnabled())
            {
                return;
            }

            new DateFolderStructure(Settings.Instance.NewsContainer, false, true, Settings.Instance.DateFolderPageTypeId.Value, "PageStartPublish").PutInDateFolder(e.Page);
        }

        /// <summary>
        /// Checks if the page is located underneath the news container
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        bool IsPageUnderNewsContainer(PageData page)
        {
            var p = page;

            while (!PageReference.IsNullOrEmpty(p.ParentLink))
            {
                // Indeed somewhere below the news container
                if (p.ParentLink==Settings.Instance.NewsContainer)
                    return true;

                // We traversed all the way up without coming across the news container
                if (p.ParentLink==PageReference.RootPage)
                    return false;

                p = p.ParentLink.GetPage();
            }

            return false;
        }

        private static bool DateFolderSortingIsEnabled()
        {
            return Settings.Instance.DateFolderPageTypeId.HasValue &&
                   !PageReference.IsNullOrEmpty(Settings.Instance.NewsContainer) &&
                   !Settings.Instance.DisableDateFolderSorting;
        }

        /// <summary>
        /// Preload is not required for this module
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        public void Preload(string[] parameters)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Uninitializes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Uninitialize(EPiServer.Framework.Initialization.InitializationEngine context)
        {
            DataFactory.Instance.CreatingPage -= CreatingPage;
            DataFactory.Instance.PublishingPage -= PublishingPage;
            _creatingPageEventAttached = false;
        }

        #endregion
    }
}
